package com.hellogood.yaohuo.server.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.hellogood.yaohuo.server.db.DBConnection;
import com.hellogood.yaohuo.shared.data.CallDTO;
import com.hellogood.yaohuo.shared.entity.YKDetail;
import com.hellogood.yaohuo.shared.entity.YKForm;
import com.hellogood.yaohuo.shared.exception.DatabaseException;

public class YKFormDAO extends FormDAO {
	Logger log = Logger.getLogger(this.getClass());

	public String createYiku(YKForm form, boolean isModify) {
		String result = "";
		List<String> sqls = new ArrayList<String>();
		if (isModify) {
			String sql = "DELETE FROM YKForm WHERE ykBillNo = '" + form.getYkBillNo() + "'";
			sqls.add(sql);
			sql = "DELETE FROM YKDetail WHERE ykBillNo = '" + form.getYkBillNo() + "'";
			sqls.add(sql);
		}
		String sql = "INSERT INTO YKForm(ykBillNo,ykDate,outOrgCode,outOrgName,inOrgCode,inOrgName,counts,cost,netCost,total,staffCode," + "staffName,rzDate,remark) VALUES('" + form.getYkBillNo()
				+ "',CONVERT(varchar(100), GETDATE(), 23),'" + form.getOutOrgCode() + "','" + form.getOutOrgName() + "','" + form.getInOrgCode() + "','" + form.getInOrgName() + "',"
				+ form.getCounts() + "," + form.getCost() + "," + form.getNetCost() + "," + form.getTotal() + ",'" + form.getStaffCode() + "','" + form.getStaffName() + "','" + form.getRzDate()
				+ "','" + form.getRemark() + "')";
		sqls.add(sql);

		List<YKDetail> list = form.getList();
		if (list != null && (!list.isEmpty())) {
			for (YKDetail d : list) {
				sql = "INSERT INTO YKDetail(ykBillNo,pluCode,pluName,orgCode,barCode,depCode,depName,bra,color,csize,jPrice,netJPrice,price," + "counts,cost,netCost,total,rzDate,remark) VALUES('"
						+ d.getYkBillNo() + "','" + d.getPluCode() + "','" + d.getPluName() + "','" + d.getOrgCode() + "','" + d.getBarCode() + "','" + d.getDepCode() + "','" + d.getDepName() + "','"
						+ d.getBra() + "','" + d.getColor() + "','" + d.getSize() + "'," + d.getjPrice() + "," + d.getNetJPrice() + "," + d.getPrice() + "," + d.getCounts() + "," + d.getCost() + ","
						+ d.getCost() + "," + d.getTotal() + ",'" + d.getRzDate() + "','" + d.getRemark() + "')";
				sqls.add(sql);
			}
		}
		try {
			executeBatch(sqls);
		} catch (DatabaseException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return e.getMessage();
		}
		return result;
	}

	public void rz(String bill) throws DatabaseException {
		CallDTO dto = new CallDTO();
		String sql = "UPDATE ykForm SET rzDate WHERE ykBillNo = '" + bill + "'";
		String call = "{CALL ykrz(?,?)}";
		dto.setBill(bill);
		dto.setCall(call);
		dto.setSql(sql);
		dto.setHxdbName(DBConnection.hxDbName);
		super.callProcedure(dto);
	}
}